package com.chat.websocket;

import com.chat.websocket.domain.ChatInfoContainer;
import com.chat.websocket.domain.MemberInfo;
import com.chat.websocket.msg.MyMessage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author 崔超
 * 2022/2/25
 */
public class BinaryWebsocketFrameHandler extends SimpleChannelInboundHandler<BinaryWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BinaryWebSocketFrame msg) throws Exception {
        ByteBuf content = msg.content();
        String containDir = UUID.randomUUID().toString();
        String dirPath = System.getProperty("user.home") + "/" + containDir;
        File dir = new File(dirPath);
        if (!dir.mkdir()) {
            throw new IOException("创建文件夹失败");
        }
        //自定义协议前100个字节是文件名
        String fileName = content.readCharSequence(100, Charset.defaultCharset()).toString().trim();
        File file = new File(dirPath + "/" + fileName);

        if (!file.createNewFile()) {
            throw new IOException("创建文件失败");
        }
        FileOutputStream outputStream = new FileOutputStream(file);
        int fileSize = content.readableBytes();
        content.readBytes(outputStream, content.readableBytes());

        MemberInfo info = ChatInfoContainer.getMemberInfo(ctx);
        String jsonMsg = MyMessage.userFile(info, fileName, fileSize / 1024, "/upload/" + containDir + "/" + fileName).toJson();
        ChatInfoContainer.sendMsgToChatRoom(ctx, jsonMsg);
    }
}
